package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody Map<String, String> user, HttpSession session) {
        //获取用户登录的手机号
        String phone = user.get("phone");
        if (StringUtils.isEmpty(phone)) {
            return R.error("请先输入手机号");
        }
        //生成6位随机数
        String code = RandomUtil.randomNumbers(6);
        log.info("code={}", code);
        //真实发送验证码
        //AliyunSmsUtil.sendSms(phone, code);
        //将生成的验证码保存到session中
        session.setAttribute(phone, code);
        return R.success("发送验证码成功");
    }

    /*
     *   用户登录
     * */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> loginUser, HttpSession session) {
//        log.info("user:{}",loginUser);
        //获取手机号和验证码
        String phone = loginUser.get("phone");
        String code = loginUser.get("code");
        //获取session中存储的验证码
        String yzm = (String) session.getAttribute(phone);
        if (yzm != null && yzm.equals(code)) {
            LambdaQueryWrapper<User> userLqw = new LambdaQueryWrapper<>();
            userLqw.eq(User::getPhone, phone);
            //查询是否为新用户
            User user = userService.getOne(userLqw);
            if (user == null) {
                //创建user对象存储用户手机号
                user = new User();
                user.setPhone(phone);
                //设置状态1
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("loginUser", user);
            return R.success(user);
        }
        return R.error("登录失败");
    }

    /*
     *   退出登录
     * */
    @PostMapping("/loginout")
    public R loginOut(HttpSession session) {
        session.removeAttribute("loginUser");
        return R.success("退出成功");
    }
}
